<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <div class="tree_main">
    <div class="left">
      <div class="title">文件列表</div>
      <el-tree
        :data="treeList"
        :props="defaultProps"
        ref="refTree"
        highlight-current
        node-key="index"
        :default-expand-all="true"
        :expand-on-click-node="false"
        :current-node-key="currentNodeKey"
        @node-click="nodeClick"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <el-icon class="icon-class" v-if="data?.children?.length > 0"><FolderOpened /></el-icon>
            <el-icon class="icon-class" v-else><FolderOpened /></el-icon>
            <span class="node-title"
              >{{ node.label }}
              <span v-if="data.modifyCount > 0 && props.active === 2" class="modify_class">{{ `「待修改项 ${data.modifyCount} 笔」` }}</span>
            </span>
          </span>
        </template>
      </el-tree>
    </div>
    <div class="split"></div>
    <div class="right">
      <div class="title">零组件列表</div>
      <el-table :data="tableData" height="calc(100vh - 281px)">
        <el-table-column type="index" label="序号" fixed="left" width="80" />
        <el-table-column prop="partNumber" label="零件号" width="160"></el-table-column>
        <el-table-column prop="versionNumber" label="版本号"></el-table-column>
        <el-table-column prop="fileSize" label="文件大小"></el-table-column>
        <el-table-column prop="fileParsingStatus" label="文件解析情况" width="160" v-if="active === 2">
          <template #default="scope">
            <div v-if="scope.row.fileParsingStatus === 1" style="color: red">该零组件已存在</div>
            <div v-if="scope.row.fileParsingStatus === 2">零组件不存在</div>
          </template>
        </el-table-column>
        <el-table-column prop="importOperationTags" label="导入操作标记" width="160" v-if="active === 2">
          <template #default="scope">
            <div v-if="scope.row.importOperationTags == 1">待标记</div>
            <div v-if="scope.row.importOperationTags == 2" style="color: #02790e">可导入</div>
            <div v-if="scope.row.importOperationTags == 3" style="color: red">不导入</div>
            <div v-if="scope.row.importOperationTags == 4" style="color: #f59a23">已修改</div>
          </template>
        </el-table-column>
        <el-table-column prop="importResultStatus" label="导入状态" width="160" v-if="active === 3">
          <template #default="scope">
            <div v-if="scope.row.importResultStatus == 1" style="color: #f59a23">修改后导入</div>
            <div v-if="scope.row.importResultStatus == 2" style="color: #02790e">导入成功</div>
            <div v-if="scope.row.importResultStatus == 3" style="color: red">未导入</div>
            <div v-if="scope.row.importResultStatus == 4">导入失败</div>
          </template>
        </el-table-column>
        <el-table-column prop="importOperationTags" label="路径" width="160" v-if="active === 3">
          <template #default="scope">
            <div>{{ scope.row.modelName }}-{{ scope.row.sectionName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" v-if="props.active === 2">
          <template #default="scope">
            <div v-if="scope.row.importOperationTags === 1">
              <el-button size="small" link type="primary" @click="handleEvent('edit', scope.row)">修改</el-button>
              <el-button size="small" link type="primary" @click="handleEvent('ignore', scope.row)">忽略</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="modifyVisible" title="修改零件" width="500">
      <el-form size="small">
        <el-form-item label="零件号">
          <el-input v-model="formData.partNum" />
        </el-form-item>
        <el-form-item label="版本号">
          <el-input v-model="formData.version" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="handleVisible">取消</el-button>
          <el-button size="small" type="primary" @click="submitModify"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script name="FileTree" setup>
import { updatePart } from '@/api/elementsLibrary';
const props = defineProps(['active', 'data']);
const emit = defineEmits(['change']);
const zipData = ref(props?.data);
const treeList = ref([]);
const formData = ref({ name: '', version: '' });
const modifyVisible = ref(false);
const defaultProps = { children: 'children', label: 'label' };
const queryParams = ref({ modelNumber: '', sectionNumber: '', componentNumber: '' });
const tableData = ref([]);
const currentData = ref(null);
const nodeData = ref(null);
const currentNodeKey = ref(2);
const refTree = ref();
//修改过的数据id集合
const modifyIds = ref([]);

// 通知父组件data已修改
const change = () => {
  emit('change', { changeData: zipData.value ,modifyDataIds:modifyIds.value});
};
//树点击事件
const nodeClick = (node, data) => {
  queryParams.value.modelNumber = '';
  queryParams.value.sectionNumber = '';
  queryParams.value.componentNumber = '';
  nodeData.value = data;
  //执行查询
  if (data.level === 1) {
    queryParams.value.modelNumber = node.label;
  }
  if (data.level === 2) {
    const parentId = data.parent.data.label;
    queryParams.value.modelNumber = parentId;
    queryParams.value.sectionNumber = node.label;
  }
  if (data.level === 3) {
    const parentId = data.parent.data.label;
    const parentId2 = data.parent.parent.data.label;
    queryParams.value.modelNumber = parentId2;
    queryParams.value.sectionNumber = parentId;
    queryParams.value.componentNumber = node.label;
  }
  tableData.value = zipData.value.filter((el) => {
    if (
      el.fileType === 'part' &&
      el.parentPath1 === queryParams.value.modelNumber &&
      el.sectionNumber === queryParams.value.sectionNumber &&
      el.componentNumber === queryParams.value.componentNumber
    ) {
      return el;
    }
  });
};
// zip包数据处理
const processZipDataList = async (query) => {
  let fileDataList = [];
  await zipData.value?.forEach((el) => {
    if (el.fileType === 'part') {
      const lastIndex = el.indexPath?.lastIndexOf('/');
      const path = el.indexPath?.slice(0, lastIndex);
      el.path = path;
      fileDataList.push(el);
    }
  });
  let list = [];
  await fileDataList?.forEach((el) => {
    const lastIndex = el.path?.lastIndexOf('/');
    const path = el.path?.slice(0, lastIndex);
    el.parentPath = path;
    list.push(el);
  });
  let rootList = [];
  await list?.forEach((el) => {
    const lastIndex = el.parentPath?.lastIndexOf('/');
    const path = el.parentPath?.slice(0, lastIndex);
    el.parentPath1 = path;
    rootList.push(el);
  });
  dataToTree(rootList, query);
};
const dataToTree = (data, query) => {
  const tree = [];
  const modelSet = new Set([]);
  const sectionSet = new Set([]);
  const componentSet = new Set([]);
  data.forEach((el) => {
    modelSet.add(el.parentPath1);
    sectionSet.add(el.parentPath);
    componentSet.add(el.path);
  });
  const modelArr = [...modelSet];
  const sectionArr = [...sectionSet];
  const componentArr = [...componentSet];
  modelArr.forEach((el) => {
    tree.push({ label: el, value: el, children: [] });
  });
  sectionArr.forEach((el) => {
    tree.forEach((item) => {
      if (el.startsWith(item.label)) {
        item.children.push({ label: el, value: el, children: [] });
      }
    });
  });
  componentArr.forEach((el) => {
    tree.forEach((item) => {
      if (item.children.length > 0) {
        item.children.forEach((k) => {
          if (el.startsWith(`${k.label}`)) {
            k.children.push({ label: el, value: el });
          }
        });
      }
    });
  });
  //去处斜杠
  let index = 0;
  tree.forEach((el) => {
    el.index = index;
    index++;
    if (el.children.length > 0) {
      el.children.forEach((item) => {
        item.index = index;
        index++;
        item.label = item.label.replace(`${el.label}/`, '');
        if (item.children.length > 0) {
          item.children.forEach(async (k) => {
            k.index = index;
            index++;
            k.label = k.label.replace(`${el.label}/${item.label}/`, '');
            //计算待修改的数据条数
            let count = 0;
            await zipData.value?.forEach((data) => {
              if (
                data.fileType === 'part' &&
                data.parentPath1 === el.label &&
                data.sectionNumber === item.label &&
                data.componentNumber === k.label &&
                data.importOperationTags === 1
              ) {
                count++;
              }
            });
            k.modifyCount = count;
          });
        }
      });
    }
  });
  treeList.value = tree;
  // 设置table数据
  if (query) {
    if (query.level === 1) {
      queryParams.value.modelNumber = query.label;
    }
    if (query.level === 2) {
      const parentId = query.parent.data.label;
      queryParams.value.modelNumber = parentId;
      queryParams.value.sectionNumber = query.label;
    }
    if (query.level === 3) {
      const parentId = query.parent.data.label;
      const parentId2 = query.parent.parent.data.label;
      queryParams.value.modelNumber = parentId2;
      queryParams.value.sectionNumber = parentId;
      queryParams.value.componentNumber = query.label;
    }
  } else {
    queryParams.value.modelNumber = tree[0]?.label;
    queryParams.value.sectionNumber = tree[0]?.children[0]?.label;
    queryParams.value.componentNumber = tree[0]?.children[0]?.children[0]?.label;
  }

  tableData.value = zipData.value.filter((el) => {
    if (
      el.fileType === 'part' &&
      el.parentPath1 === queryParams.value.modelNumber &&
      el.sectionNumber === queryParams.value.sectionNumber &&
      el.componentNumber === queryParams.value.componentNumber
    ) {
      return el;
    }
  });
};
//点击事件
const handleEvent = (type, data) => {
  currentData.value = data;
  if (type === 'edit') {
    modifyVisible.value = true;
    formData.value.version = data.versionNumber;
    formData.value.partNum = data.partNumber;
  }
  if (type === 'ignore') {
    ElMessageBox.confirm('忽略后该文件将不会被导入，请确认是否忽略。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      zipData.value.find((el) => {
        if (el.partName === data.partName || el.id === data.id) {
          el.importOperationTags = 3;
        }
      });
    });
  }
};
// 提交修改
const submitModify = () => {
  let data = { ...currentData.value };
  data.versionNumber = formData.value.version;
  data.partNumber = formData.value.partNum;
  data.fileParsingStatus = 2;
  data.importOperationTags = 2;
  // 提交修改
  updatePart(data).then((res) => {
    if (res.code === 200) {
      // 设置当前数据ID为最新ID
      data.id = res?.data.id;
      modifyIds.value.push(res?.data.id);
      zipData.value.find((el) => {
        if (el.partName === data.partName || el.id === data.id) {
          el.fileParsingStatus = 2;
          el.importOperationTags = 2;
          el.versionNumber = formData.value.version;
          el.partNumber = formData.value.partNum;
          el.id = res?.data.id;
        }
      });
      ElMessage({ message: '修改成功', type: 'success', close: true });
      handleVisible();
      // 通知父组件
      change();
      processZipDataList(nodeData.value);
      currentNodeKey.value = nodeData.value.data.index;
      refTree.value.setCurrentKey(currentNodeKey.value);
    }
  });
};
const handleVisible = () => {
  modifyVisible.value = false;
};
onMounted(() => {
  processZipDataList();
});
</script>
<style lang="scss" scoped>
.tree_main {
  display: flex;
  width: 100%;
  height: 100%;
  font-size: 12px;
  .left {
    width: 300px;
    height: 100%;
    overflow: auto;
    .title {
      margin-bottom: 5px;
    }
    .custom-tree-node {
      display: flex;
      .icon-class {
        color: #ffcc66;
        font-size: 120%;
      }
      .node-title {
        padding-left: 5px;
        font-size: 12px;
        .modify_class {
          font-size: 12px;
          color: #409eff;
        }
      }
    }
  }
  .split {
    height: 100%;
    width: 2px;
    background: #dcdfe6;
    margin-right: 8px;
    margin-top: 20px;
    height: 100%;
    overflow: hidden;
  }
  .right {
    padding: 4px;
    width: calc(100% - 300px);
    height: 100%;
    // overflow: auto;
    .title {
      margin-bottom: 5px;
    }
  }
}
</style>